package com.lb.ai.common.response;

import com.lb.ai.common.response.code.ResultCodeContainer;

import java.util.function.Supplier;

/**
 * 响应结果建造者
 *
 * @author LiuB
 */
public class ResultBuilder<T> {
    private final Result<T> result;
    private final ResultCodeContainer resultCodeContainer = ResultCodeContainer.getInstance();

    private ResultBuilder() {
        result = new Result<>();
        result.setTimestamp(System.currentTimeMillis());
    }

    public static <T> ResultBuilder<T> create() {
        return new ResultBuilder<>();
    }

    public ResultBuilder<T> code(IResultCode resultCode) {
        result.setCode(resultCode.getCode());
        result.setMessage(resultCode.getMessage());
        result.setSuccess(resultCodeContainer.isSuccess(resultCode.getCode()));
        return this;
    }

    public ResultBuilder<T> code(Integer code) {
        IResultCode resultCode = resultCodeContainer.getCode(code);
        if (resultCode != null) {
            return code(resultCode);
        }
        result.setCode(code);
        result.setSuccess(resultCodeContainer.isSuccess(code));
        return this;
    }

    public ResultBuilder<T> message(String message) {
        result.setMessage(message);
        return this;
    }

    public ResultBuilder<T> data(T data) {
        result.setData(data);
        return this;
    }

    public ResultBuilder<T> success(boolean success) {
        result.setSuccess(success);
        return this;
    }

    public ResultBuilder<T> throwOnError(Supplier<? extends RuntimeException> exceptionSupplier) {
        if (!result.isSuccess() && exceptionSupplier != null) {
            throw exceptionSupplier.get();
        }
        return this;
    }

    public Result<T> build() {
        return result;
    }
} 